/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.smb

import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import jcifs.smb.SmbFile
import jcifs.smb.SmbFileInputStream
import jcifs.smb.SmbFileOutputStream
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory

/**
 * SmbUtils.download(new SmbFile("smb://admin:purplekayak675@192.168.1.4/share_sda1/stock_download/"), new File("./usecase/"));
 * SmbUtils.upload(new File("/home/rcmu/workspace/test"),new SmbFile("smb://admin:purplekayak675@192.168.1.4/share_sda1/"));
 */
class SmbUtils {
	val static LOG = LoggerFactory.getLogger(SmbUtils);

	def static void download(SmbFile smbFile, File localFile) {
		if (smbFile.exists) {
			var sfiles = smbFile.listFiles;
			sfiles.forEach [
				if (it.directory) {
					var dir = new File(#[localFile.absolutePath,it.name].join(File.separator));
					if(!dir.exists){
						dir.mkdirs;
					}
					download(it, dir);
				} else if (it.file) {
					if (localFile !== null && localFile.exists) {
						LOG.info("下载{} 至 {}",it.getPath,localFile.absolutePath);
						try(var in = new BufferedInputStream(new SmbFileInputStream(it))) {
							try(var out = new BufferedOutputStream(new FileOutputStream(new File(#[localFile.absolutePath,it.name].join(File.separator))))) {
								IOUtils.copy(in, out);
							}
						} catch (Exception ex) {
							ex.printStackTrace
						}
					}
				}
			]
		}
	}

	def static void upload( File localFile,SmbFile smbFile) {
		if (localFile.exists) {
			var sfiles = localFile.listFiles;
			sfiles.forEach [
				if (it.directory) {
					var dir = new SmbFile(#[smbFile.path,it.name].join(File.separator));
					if(!dir.exists){
						dir.mkdirs;
					}
					upload(it, dir);
				} else if (it.file) {
					if (smbFile !== null && smbFile.exists) {
						LOG.info("上传 {} 至 {}",localFile.absolutePath,it.getPath);
						try(var in = new BufferedInputStream(new FileInputStream(it))) {
							try(var out = new BufferedOutputStream(new SmbFileOutputStream(new SmbFile(#[smbFile.path,it.name].join(File.separator))))) {
								IOUtils.copy(in, out);
							}
						} catch (Exception ex) {
							ex.printStackTrace
						}
					}
				}
			]
		}
	}

}
